package com.skycan.plc.adapter.netty.handler;

import com.skycan.plc.adapter.model.DeviceInfo;
import com.skycan.plc.adapter.service.DeviceService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;

/**
 * 设备消息处理器
 */
public class DeviceMessageHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(DeviceMessageHandler.class);

    private final DeviceService deviceService;
    private String deviceId;

    public DeviceMessageHandler(DeviceService deviceService) {
        this.deviceService = deviceService;
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        InetSocketAddress address = (InetSocketAddress) ctx.channel().remoteAddress();
        String ipAddress = address.getAddress().getHostAddress();
        int port = address.getPort();

        // 使用IP地址:端口作为临时设备ID
        deviceId = ipAddress + ":" + port;

        logger.info("设备连接建立: {}", deviceId);

        // 在设备服务中注册设备
        DeviceInfo deviceInfo = DeviceInfo.builder()
                .deviceId(deviceId)
                .ipAddress(ipAddress)
                .port(port)
                .status(DeviceInfo.DeviceStatus.ONLINE)
                .lastCommunicationTime(System.currentTimeMillis())
                .build();

        deviceService.registerDevice(deviceInfo, ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        logger.info("设备连接断开: {}", deviceId);

        // 更新设备状态为离线
        deviceService.updateDeviceStatus(deviceId, DeviceInfo.DeviceStatus.OFFLINE);

        // 移除设备通道
        deviceService.removeDeviceChannel(deviceId);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        if (msg instanceof byte[]) {
            byte[] data = (byte[]) msg;
            logger.debug("处理设备消息: {}, 长度: {}", deviceId, data.length);

            // 更新设备最后通信时间
            deviceService.updateLastCommunicationTime(deviceId, System.currentTimeMillis());

            // 处理设备消息
            // 实际应用可以根据不同设备的消息内容进行处理
            // deviceService.processDeviceMessage(deviceId, data);
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;

            if (e.state() == IdleState.READER_IDLE || e.state() == IdleState.WRITER_IDLE) {
                logger.warn("设备心跳超时: {}, 状态: {}", deviceId, e.state());

                // 超时关闭连接
                ctx.close();
            }
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        logger.error("设备通信异常: {}, 错误: {}", deviceId, cause.getMessage());

        // 更新设备状态为错误
        deviceService.updateDeviceStatus(deviceId, DeviceInfo.DeviceStatus.ERROR);

        // 关闭连接
        ctx.close();
    }
}